package com.aorise.controller.migration;

import com.aorise.exception.ServiceException;
import com.aorise.model.migration.*;
import com.aorise.service.migration.MigrationService;
import com.aorise.utils.ConstDefine;
import com.aorise.utils.StatusDefine;
import com.aorise.utils.StatusDefineMessage;
import com.aorise.utils.json.JsonResponseData;
import com.aorise.utils.page.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author:cat
 * @Desicription: 点位迁建控制器类
 * @Date:Created in 2019-06-01
 * @Modified By:
 */
@RestController
@Api(description ="点位迁建信息接口")
public class MigrationController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MigrationService migrationService;

    /**
     * 根据筛选条件进行分页查询迁建记录信息
     * HTTP 方式：GET
     * API 路径：/api/migration/pageIndex/{pageIndex}/pageNum/{pageNum}
     * 方法名：getAllMigrationListByPage
     * 方法返回类型：String
     *
     * @Author: cat
     * @Date: 2019-06-03
     */
    @ApiOperation(value = "根据筛选条件进行分页查询迁建记录信息", httpMethod = "GET", response = String.class, notes = "根据筛选条件进行分页查询迁建记录信息,提供点位迁建管理-查询列表使用")
    @RequestMapping(value = "/api/migration/pageIndex/{pageIndex}/pageNum/{pageNum}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getAllMigrationListByPage(@ApiParam(value = "起始申请日期", required = false) @RequestParam(value = "startCreateTime", required = false) String startCreateTime,
                                         @ApiParam(value = "截止申请日期", required = false) @RequestParam(value = "endCreateTime", required = false) String endCreateTime,
                                         @ApiParam(value = "迁建原因", required = false) @RequestParam(value = "reason", required = false) String reason,
                                         @ApiParam(value = "申请状态：1待审批，2通过，3驳回", required = false) @RequestParam(value = "status", required = false) Integer status,
                                         @ApiParam(value = "登录人ID", required = true) @RequestParam(value = "userId", required = true) Integer userId,
                                         @ApiParam(value = "页索引", required = true) @PathVariable(value = "pageIndex", required = true) String pageIndex,
                                         @ApiParam(value = "页大小", required = true) @PathVariable(value = "pageNum", required = true) String pageNum) {
        logger.debug("Request RESTful API:getAllMigrationListByPage");
        logger.debug("startCreateTime：" + startCreateTime);
        logger.debug("endCreateTime：" + endCreateTime);
        logger.debug("reason：" + reason);
        logger.debug("status：" + status);
        logger.debug("userId：" + userId);
        logger.debug("pageIndex" + pageIndex);
        logger.debug("pageNum" + pageNum);

        Page page = new Page();
        if (!StringUtils.isBlank(pageIndex)) {
            page.setCurrentPage(Long.parseLong(pageIndex.toString()));
        }
        if (!StringUtils.isBlank(pageNum)) {
            page.setEveryPage(Long.parseLong(pageNum.toString()));
        }
        try {

            Map<String, Object> map = new HashMap<>();
            map.put("startCreateTime", startCreateTime);
            map.put("endCreateTime", endCreateTime);
            map.put("reason", reason);
            map.put("status", status);
            map.put("userId", userId);
            map.put("isReadNo", ConstDefine.ISREAD_NO);
            map.put("isRead", ConstDefine.ISREAD);
            map.put("state", ConstDefine.STATE_ABLE);
            map.put("beginIndex", page.getBeginIndex());
            map.put("endinIndex", page.getEndinIndex());

            List<MigrationModel> migrationModels = migrationService.getAllMigrationListByPage(map, page);
            page.setList(migrationModels);

            return new JsonResponseData(true,
                    StatusDefineMessage.GetMessage(StatusDefine.SUCCESS), StatusDefine.SUCCESS, "", page).toString();
        } catch (DataAccessException e) {
            logger.error(
                    "controller:MigrationController. function:getAllMigrationListByPage...msg:Get Migration List By Page DataAccessException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), page).toString();
        } catch (Exception e) {
            logger.error(
                    "controller:MigrationController. function:getAllMigrationListByPage...msg:Get Migration List By Page Exception. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), page).toString();
        }
    }

    /**
     * 根据ID查询迁建记录详情
     * HTTP 方式：GET
     * API 路径：/api/migration/id/{id}
     * 方法名：getMigrationById
     * 方法返回类型：String
     *
     * @Author: cat
     * @Date: 2019-06-03
     */
    @ApiOperation(value = "根据ID查询迁建记录详情", httpMethod = "GET", response = String.class, notes = "根据ID查询迁建记录详情，提供点位迁建管理-查询迁建记录详情使用")
    @RequestMapping(value = "/api/migration/id/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getMigrationById(@ApiParam(value = "ID", required = true) @PathVariable(value = "id", required = true) Integer id,
                                   @ApiParam(value = "登录人ID", required = true) @RequestParam(value = "userId", required = true) Integer userId) {

        logger.debug("Request RESTful API:getMigrationById");
        logger.debug("id" + id);
        logger.debug("userId" + userId);
        try {
            MigrationModel migrationModel = migrationService.getMigrationById(id,userId);
            return new JsonResponseData(true,
                    StatusDefineMessage.GetMessage(StatusDefine.SUCCESS), StatusDefine.SUCCESS, "",migrationModel).toString();
        } catch (DataAccessException e) {
            logger.error(
                    "controller:MigrationController. function:getMigrationById...msg:Get Migration By Id DataAccessException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            logger.error(
                    "controller:MigrationController. function:getMigrationById...msg:Get Migration By Id Exception. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
    }

    /**
     * 新增迁建记录信息
     * HTTP 方式：POST
     * API 路径：/api/migration
     * 方法名：addMigration
     * 方法返回类型：String
     *
     * @Author: cat
     * @Date: 2019-06-03
     */
    @ApiOperation(value = "新增迁建记录信息", httpMethod = "POST", response = String.class, notes = "新增迁建记录信息，提供点位迁建管理-创建申请使用")
    @RequestMapping(value = "/api/migration", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody
    String addMigration(@RequestBody @Validated MigrationAddVO migrationAddVO, BindingResult result) {

        logger.debug("Request RESTful API:addMigration");
        logger.debug("migrationAddVO：" + migrationAddVO);

        try {
            if (result.hasErrors()) {
                return JsonResponseData.ofMessage(StatusDefine.DATA_FORMAT_ERROR, result.getFieldError().getDefaultMessage());
            }

            /**替换空字符串值*/
            if (migrationAddVO.getHisLongitude().equals("")) {
                migrationAddVO.setHisLongitude(null);
            }
            if (migrationAddVO.getHisLatitude().equals("")) {
                migrationAddVO.setHisLatitude(null);
            }
            if (migrationAddVO.getNewLongitude().equals("")) {
                migrationAddVO.setNewLongitude(null);
            }
            if (migrationAddVO.getNewLatitude().equals("")) {
                migrationAddVO.setNewLatitude(null);
            }
            int ret = migrationService.addMigration(migrationAddVO);

            if (ret > 0) {
                return new JsonResponseData(true,
                        StatusDefineMessage.GetMessage(StatusDefine.SUCCESS), StatusDefine.SUCCESS, "", ret).toString();
            } else {
                return new JsonResponseData(false,
                        "", StatusDefine.FAILURE, StatusDefineMessage.GetMessage(StatusDefine.FAILURE), "").toString();
            }
        } catch (DataAccessException e) {
            logger.error(
                    "controller:MigrationController. function:addMigration...msg:Add Migration DataAccessException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (ServiceException e) {
            logger.error(
                    "controller:MigrationController. function:addMigration...msg:Add Migration ServiceException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.CAMERA_NULL,
                    e.getMessage(), null).toString();
        } catch (Exception e) {
            logger.error(
                    "controller:MigrationController. function:addMigration...msg:Add Migration Exception. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
    }

    /**
     * 删除迁建记录信息
     * HTTP 方式：DELETE
     * API 路径：/api/migration/id/{id}
     * 方法名：deleteMigration
     * 方法返回类型：String
     *
     * @Author: cat
     * @Date: 2019-06-03
     */
    @ApiOperation(value = "删除迁建记录信息", httpMethod = "DELETE", response = String.class, notes = "删除迁建记录信息，提供点位迁建管理-撤回点位迁建申请使用")
    @RequestMapping(value = "/api/migration/id/{id}", method = RequestMethod.DELETE, produces = "application/json")
    public String deleteMigration(@ApiParam(value = "ID", required = true) @PathVariable(value = "id", required = true) Integer id,
                              @ApiParam(value = "修改人ID", required = true) @RequestParam(value = "editUser", required = true) Integer editUser) {
        logger.debug("Request RESTful API:deleteMigration");
        logger.debug("id" + id);
        logger.debug("editUser" + editUser);

        try {
            Map<String, Object> map = new HashMap<>();
            map.put("editUser", editUser);
            map.put("state", ConstDefine.STATE_DISABLE);
            map.put("id", id);
            int ret = migrationService.deleteMigration(map);

            if (ret > 0) {
                return new JsonResponseData(true,
                        StatusDefineMessage.GetMessage(StatusDefine.SUCCESS), StatusDefine.SUCCESS, "", "").toString();
            } else {
                return new JsonResponseData(false,
                        "", StatusDefine.FAILURE, StatusDefineMessage.GetMessage(StatusDefine.FAILURE), "").toString();
            }
        } catch (DataAccessException e) {
            logger.error(
                    "controller:MigrationController. function:deleteMigration...msg:Delete Migration DataAccessException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (ServiceException e) {
            logger.error(
                    "controller:MigrationController. function:deleteMigration...msg:Delete Migration ServiceException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.APPLICATION_DELETE,
                    e.getMessage(), null).toString();
        } catch (Exception e) {
            logger.error(
                    "controller:MigrationController. function:deleteMigration...msg:Delete Migration Exception. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
    }

    /**
     * 查询迁建记录未读消息总数
     * HTTP 方式：GET
     * API 路径：/api/migration/getMigrationIsNotRead/userId/{userId}
     * 方法名：getMigrationIsNotRead
     * 方法返回类型：String
     *
     * @Author: cat
     * @Date: 2019-06-03
     */
    @ApiOperation(value = "查询迁建记录未读消息总数", httpMethod = "GET", response = String.class, notes = "查询迁建记录未读消息总数，提供导航上点位迁建管理查询提醒数使用")
    @RequestMapping(value = "/api/migration/getMigrationIsNotRead/userId/{userId}", method = RequestMethod.GET, produces = "application/json")
    public String getMigrationIsNotRead(@ApiParam(value = "登录人ID", required = true) @PathVariable(value = "userId", required = true) Integer userId) {
        logger.debug("Request RESTful API:getMigrationIsNotRead");
        logger.debug("userId" + userId);

        try {
            Map<String, Object> map = new HashMap<>();
            map.put("userId", userId);
            Long ret = migrationService.getMigrationIsNotRead(map);
            return new JsonResponseData(true,
                    StatusDefineMessage.GetMessage(StatusDefine.SUCCESS), StatusDefine.SUCCESS, "", ret).toString();
        } catch (DataAccessException e) {
            logger.error(
                    "controller:MigrationController. function:getMigrationIsNotRead...msg:Get Migration Is Not Read DataAccessException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            logger.error(
                    "controller:MigrationController. function:getMigrationIsNotRead...msg:Get Migration Is Not Read Exception. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
    }

}
